package com.cn.algorithm.two.line.test;

import java.util.Arrays;

public class RadixSortJ {
    public static void main(String[] args) {
        int[] arr = {9, 7, 4, 200, 5, 30, 8};
        sort(arr);
        System.out.println(Arrays.toString(arr));
    }

    public static void sort(int[] arr) {
        if (arr == null || arr.length <= 1) {
            return;
        }
        int max = arr[0];
        for (int i = 1; i < arr.length; i++) {
            if (arr[i] > max) {
                max = arr[i];
            }
        }
        for (int i = 1; max / i > 0; i *= 10) {
            radix(arr, i);
        }
    }

    public static void radix(int[] arr, int tmp) {
        int[] buckets = new int[10];
        for (int i = 0; i < arr.length; i++) {
            buckets[arr[i] / tmp % 10]++;
        }
        for (int i = 1; i < buckets.length; i++) {
            buckets[i] += buckets[i - 1];
        }
        int[] outs = new int[arr.length];
        for (int i = arr.length - 1; i >= 0; i--) {
            outs[buckets[arr[i] / tmp % 10] - 1] = arr[i];
            buckets[arr[i] / tmp % 10]--;
        }
        for (int i = 0; i < outs.length; i++) {
            arr[i] = outs[i];
        }
        outs = null;
    }
}
